package com.dobest.base.date;

import cn.hutool.core.date.LocalDateTimeUtil;
import org.junit.jupiter.api.Test;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author huangy
 * @description
 * @since 2022/10/24 15:25
 **/
public class TimeUtils {

    public static void main(String[] args) throws InterruptedException {
        long beforeTimestamp = Instant.now().toEpochMilli();
        System.out.println("before: " + beforeTimestamp);
        Thread.sleep(2000);
        System.out.println("interval: " + getMinute2Now(beforeTimestamp));
    }

    /*
     * @description 计算时间戳与当前时间所差的分钟数
     * @author huangy
     * @since 2022/10/24 15:57
     * @param before
     * @return int
     **/
    public static double getMinute2Now(double before) {
        long nowTimestamp = Instant.now().toEpochMilli();
        return (nowTimestamp - before) / (1000 * 60);
    }

    @Test
    public void weekNum() {
        int dayNum = 35;
        calDay(dayNum);
    }

    private static void calDay(int dayNum) {
        //通过天数计算是第几周第几天
        int theDay = dayNum % 7 - 1;
        if (theDay < 0) {
            theDay += 7;
        }
        //天数里总共有几周
        int weekNum = dayNum / 7;
        if (weekNum == 0) {
            weekNum += 1;
        }
        int theWeek = weekNum % 4;
        if (theWeek == 0) {
            theWeek = 4;
        }
        System.out.printf("这是循环的第%d周, %d天%n", theWeek, theDay);
    }

    @Test
    public void dayOfTime() {
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前是本周的第" + now.getDayOfWeek().getValue() + "天");
        System.out.println("当前是本月的第" + now.getDayOfMonth() + "天");
    }

    @Test
    public void sameMonth() {
        LocalDateTime time1 = LocalDateTime.of(2021, 1, 5, 0, 0, 0);
        LocalDateTime time2 = LocalDateTime.of(2021, 1, 5, 0, 0, 0);
        System.out.println((time1.getYear() == time2.getYear() && time1.getMonth().equals(time2.getMonth())));
    }

    @Test
    public void sameDay() {
        LocalDateTime lastTime = LocalDateTime.of(2021, 1, 4, 23, 59, 59);
        LocalDateTime nowTime = LocalDateTime.of(2021, 1, 5, 0, 0, 0);
        System.out.println(LocalDateTimeUtil.isSameDay(lastTime, nowTime));
    }

    @Test
    public void timestampToDate() {
        long timestamp = 1678696947604L;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = sdf.format(new Date(timestamp));
        System.out.println(sd);
    }

}
